package com.newer.SelectorGenerator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class Tools {
	public static boolean isNotEmpty(String txt) {
		return txt != null && txt.trim().length() > 0;
	}
	
	public static boolean isEmpty(String txt){
		return !isNotEmpty(txt);
	}
	
	/**获得去掉扩展名的文件名*/
	public static String getFileNameWithOutTypeName(String fileName){
		int position =fileName.indexOf(".");
		if(position>=0){
			return fileName.substring(0, fileName.indexOf("."));
		}
		return "";
	}
	
	/**从文件名中获得主要名字  如ab_d_nor.xml中的ab_d,按最后一个"_"截取*/
	public static String getMainFileNameFromFileName(String fileName){
		int position=fileName.lastIndexOf("_");
		if(position>=0){
			return fileName.substring(0,fileName.lastIndexOf("_"));
		}
		return "";
	}
	
	/** 保存文件 charset为null时,则默认"UTF-8"*/
	public static boolean saveFile(String filePath, String content,String charset) {
		if(isEmpty(filePath)){
			return false;
		}
		File outFile = new File(filePath);
		int errNum=0;
		outFile.getParentFile().mkdirs();
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(outFile), Tools.isNotEmpty(charset)?charset:"UTF-8");
			osw.write(content);
			osw.flush();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			errNum++;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			errNum++;
		} catch (IOException e) {
			e.printStackTrace();
			errNum++;
		} finally {
			if (osw != null) {
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return errNum>0;
	}
}
